<template>
  <div class="user-avatar-container">
    <div class="user-info-avatar" @click="editCropper">
      <img
        v-if="avatar && !isAvatarError"
        class="preview"
        :src="avatar"
        @error="previewError"
        alt=""
      />
      <img v-else class="preview default-avatar" :src="defaultAvatar" alt="" />
    </div>

    <common-dialog
      :title="title"
      width="600px"
      :visible.sync="isAvatarDialog"
      @close="closeDialog"
    >
      <div class="avatar-upload-wrap">
        <div class="avatar-operate-container">
          <div class="avatar-cropper-container">
            <vue-cropper
              ref="cropper"
              :img="options.img || avatar"
              :info="true"
              :autoCrop="options.autoCrop"
              :autoCropWidth="options.autoCropWidth"
              :autoCropHeight="options.autoCropHeight"
              :fixedBox="options.fixedBox"
              @realTime="realTime"
            />
          </div>
          <div class="avatar-cropper-preview">
            <img :src="previews.url" :style="previews.img" alt="" />
          </div>
        </div>

        <div class="avatar-operate-footer">
          <div class="avatar-operate-button-group">
            <el-upload
              style="margin-right: 8px"
              action="#"
              :http-request="requestUpload"
              :show-file-list="false"
              :before-upload="beforeUpload"
            >
              <el-button>
                选择
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
            </el-upload>
            <el-button icon="el-icon-plus" @click="changeScale(1)"></el-button>
            <el-button
              icon="el-icon-minus"
              @click="changeScale(-1)"
            ></el-button>
            <el-button
              icon="el-icon-refresh-left"
              @click="rotateLeft()"
            ></el-button>
            <el-button
              icon="el-icon-refresh-right"
              @click="rotateRight()"
            ></el-button>
          </div>
          <el-button
            type="primary"
            @click="uploadImg()"
            :loading="submitLoading"
            >提 交</el-button
          >
        </div>
      </div>
    </common-dialog>
  </div>
</template>

<script>
import { VueCropper } from "vue-cropper";
import { getUserPic, upLoadUserPic } from "@/api/person";
import CommonDialog from "@/components/CommonDialog";

import UserAvatar from "@/assets/images/user-avatar.jpeg";
import { mapGetters } from "vuex";

export default {
  components: { VueCropper, CommonDialog },
  props: {
    user: {
      type: Object,
    },
  },
  data() {
    return {
      // 是否显示弹出层
      isAvatarDialog: false,
      defaultAvatar: UserAvatar,
      isAvatarError: false,
      // 弹出层标题
      title: "编辑头像",
      options: {
        img: this.$store.getters.avatar, //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
      },
      previews: {},
      submitLoading: false,
    };
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  methods: {
    previewError() {
      this.isAvatarError = true;
    },
    // 编辑头像
    editCropper() {
      this.isAvatarDialog = true;
    },
    // 覆盖默认的上传行为
    requestUpload() {},
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") === -1) {
        this.$GlobalErrorConfirm(
          "文件格式错误",
          "请上传图片类型,如JPG，PNG后缀的文件。"
        );
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.options.img = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob((data) => {
        // console.log(444444, data)
        let formData = new FormData();
        formData.append("avatarfile", data);
        this.submitLoading = true;
        upLoadUserPic(formData)
          .then((res) => {
            if (res && res.code === 200) {
              this.isAvatarDialog = false;
              this.getUserAvatar(res.data);
              this.$GlobalSuccessMessage("头像上传成功");
            } else {
              this.$GlobalErrorConfirm("头像上传失败", res.msg);
            }
          })
          .finally(() => (this.submitLoading = false));
      });
    },
    getUserAvatar(path) {
      getUserPic(path).then((res) => {
        if (res && res.code === 200) {
          this.$store.commit("SET_AVATAR", `data:image/png;base64,${res.data}`);
        } else {
          this.$store.commit("SET_AVATAR", null);
        }
      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      this.isAvatarDialog = false;
    },
  },
};
</script>
<style scoped lang="scss">
.user-avatar-container {
  .user-info-avatar {
    position: relative;
    display: inline-block;
    width: 158px;
    height: 158px;
    cursor: pointer;

    .preview {
      width: 158px;
      height: 158px;
      position: absolute;
      left: 0;
      top: 0;
    }

    .default-avatar {
      z-index: 9;
    }
  }

  .user-info-avatar:hover:after {
    content: "+";
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 158px;
    height: 158px;
    line-height: 158px;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    cursor: pointer;
    text-align: center;
    font-size: 40px;
  }
}

.avatar-upload-wrap {
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;

  .avatar-operate-container {
    width: 100%;
    height: 336px;
    display: flex;
    padding: 18px;
    box-sizing: border-box;
    border-bottom: 1px solid #eee;

    .avatar-cropper-container {
      width: 300px;
      height: 300px;
    }

    .avatar-cropper-preview {
      width: 200px;
      height: 200px;
      margin: 50px;
      box-sizing: border-box;
      overflow: hidden;

      img {
        width: 200px;
        height: 200px;
      }
    }
  }

  .avatar-operate-footer {
    width: 100%;
    height: 68px;
    display: flex;
    padding: 18px;
    align-items: center;
    justify-content: space-between;

    .avatar-operate-button-group {
      display: flex;
      align-items: center;
    }
  }
}
</style>
